package com.zoffy.wmsbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoffy.wmsbackend.common.RequestParam;
import com.zoffy.wmsbackend.mapper.ManufacturerMapper;
import com.zoffy.wmsbackend.model.dto.manufacturer.ManufacturerDTO;
import com.zoffy.wmsbackend.model.entity.Manufacturer;
import com.zoffy.wmsbackend.model.vo.ManufacturerVO;
import com.zoffy.wmsbackend.service.ManufacturerService;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ManufacturerServiceImpl extends ServiceImpl<ManufacturerMapper, Manufacturer> implements ManufacturerService {

    @Override
    public IPage<ManufacturerVO> listManufacturerPage(RequestParam<ManufacturerDTO> requestParam) {
        long current = requestParam.getPageNum();
        long size = requestParam.getPageSize();
        ManufacturerDTO params = requestParam.getParams();
        String code = params.getCode();
        String name = params.getName();
        Page<Manufacturer> page = new Page<>(current, size);
        QueryWrapper<Manufacturer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtil.isNotBlank(code),"code", code);
        queryWrapper.like(StringUtil.isNotBlank(name),"name","%"+ name+"%");
        IPage<Manufacturer> manufacturerPage = this.page(page, queryWrapper);
        List<ManufacturerVO> manufacturerVOList = manufacturerPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        IPage<ManufacturerVO> voPage = new Page<>(manufacturerPage.getCurrent(), manufacturerPage.getSize(), manufacturerPage.getTotal());
        voPage.setRecords(manufacturerVOList);
        return voPage;
    }

    private ManufacturerVO convertToVO(Manufacturer manufacturer) {
        ManufacturerVO vo = new ManufacturerVO();
        vo.setId(manufacturer.getId());
        vo.setName(manufacturer.getName());
        vo.setCode(manufacturer.getCode());
        return vo;
    }

    @Override
    public Boolean addManufacturer(ManufacturerDTO dto) {
        Manufacturer manufacturer = new Manufacturer();
        manufacturer.setName(dto.getName());
        manufacturer.setCode(dto.getCode());
        return this.save(manufacturer);
    }
}